package com.example.java8.feature_06;

import java.util.Collection;
import java.util.HashSet;
import java.util.function.IntConsumer;
import java.util.function.Predicate;
import java.util.function.ToIntFunction;

public class TestStreamCollection {

	public static void main(String[] args){
		
		test();
		testToJava7();
	}
	
	public static void test(){
		//创建一个集合
		Collection colls = new HashSet();
		colls.add(new String("deleerhai"));
		colls.add(new String("tongtong"));
		colls.add(new String("huangxiaohei"));
		colls.add(new String("I Love You"));
		colls.add(new String("hello"));
		
		//统计集合包含hai子串的字符串对象的数量
		System.out.println(colls.stream().filter(ele -> ((String) ele).contains("hai")).count());
		//统计集合包含tong子串的字符串对象的数量
		System.out.println(colls.stream().filter(ele -> ((String) ele).contains("tong")).count());
		//统计集合中字符串长度大于6的数量
		System.out.println(colls.stream().filter(ele -> ((String) ele).length() > 6).count());
		
		//先调用Collection对象的stream()方法将集合转换为Stream
		//在调用Stream的mapToInt()方法获取原有的Stream对应的IntStream
		//并调用forEach()方法遍历IntStream中每个元素
		colls.stream().mapToInt(ele -> ((String) ele).length()).forEach(System.out :: println);
	}
	
	/**
	 * 改成Java7写法
	 * */
	public static void testToJava7(){
		//创建一个集合
		Collection colls = new HashSet();
		colls.add(new String("deleerhai"));
		colls.add(new String("tongtong"));
		colls.add(new String("huangxiaohei"));
		colls.add(new String("I Love You"));
		colls.add(new String("hello"));
		
		//统计集合包含hai子串的字符串对象的数量
		long count1 = colls.stream().filter(new Predicate() {
			@Override
			public boolean test(Object obj) {
				return ((String) obj).contains("hai");
			}
		}).count();
		System.out.println(count1);
		
		//统计集合包含tong子串的字符串对象的数量
		long coutn2 = colls.stream().filter(new Predicate() {
			@Override
			public boolean test(Object obj) {
				
				return ((String) obj).contains("tong");
			}
		}).count();
		System.out.println(coutn2);
		//统计集合中字符串长度大于6的数量
		long count3 = colls.stream().filter(new Predicate() {
			@Override
			public boolean test(Object obj) {
				return ((String) obj).length() > 6;
			}
		}).count();
		System.out.println(count3);
		
		//先调用Collection对象的stream()方法将集合转换为Stream
		//在调用Stream的mapToInt()方法获取原有的Stream对应的IntStream
		//并调用forEach()方法遍历IntStream中每个元素
		colls.stream().mapToInt(new ToIntFunction() {

			@Override
			public int applyAsInt(Object value) {
				return ((String) value).length();
			}
		}).forEach(new IntConsumer() {
			@Override
			public void accept(int value) {
				System.out.println(value);
			}
		});
	}
}
